<!DOCTYPE html>
<html lang="zh-Hans">
<head>

    <!--[if lt IE 9]>
        <style>body {display: none; background: none !important} </style>
        <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" />
    <![endif]-->

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no" />
<meta name="author" content="王诗翔" />


    
    


<meta name="description" content="记录生活，编码数据">
<meta property="og:type" content="website">
<meta property="og:title" content="Cloudberry">
<meta property="og:url" content="https://shixiangwang.github.io/page/2/index.html">
<meta property="og:site_name" content="Cloudberry">
<meta property="og:description" content="记录生活，编码数据">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Cloudberry">
<meta name="twitter:description" content="记录生活，编码数据">

<link rel="apple-touch-icon" href= "/apple-touch-icon.png">


    <link rel="alternate" href="/atom.xml" title="Cloudberry" type="application/atom+xml">



    <link rel="shortcut icon" href="/favicon.png">



    <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet">



    <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet">



    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">


<link rel="stylesheet" href="../../css/style.css">


    <style> .article { opacity: 0;} </style>


<link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


<title>Cloudberry</title>

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

<script>
    var yiliaConfig = {
        fancybox: true,
        animate: true,
        isHome: true,
        isPost: false,
        isArchive: false,
        isTag: false,
        isCategory: false,
        fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js",
        scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js",
        search: true
    }
</script>


    <script>
        yiliaConfig.jquery_ui = [true, "//cdn.bootcss.com/jqueryui/1.10.4/jquery-ui.min.js", "//cdn.bootcss.com/jqueryui/1.10.4/css/jquery-ui.min.css"];
    </script>



    <script> yiliaConfig.rootUrl = "\/";</script>






</head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <a href="/" class="profilepic">
            <img src="/img/avatar.png" class="animated zoomIn">
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/">王诗翔</a></h1>
        </hgroup>

        
        <p class="header-subtitle">A site for writing life</p>
        

        
            <form id="search-form">
            <input type="text" id="local-search-input" name="q" placeholder="search..." class="search form-control" autocomplete="off" autocorrect="off" searchonload="false" />
            <i class="fa fa-times" onclick="resetSearch()"></i>
            </form>
            <div id="local-search-result"></div>
            <p class='no-result'>No results found <i class='fa fa-spinner fa-pulse'></i></p>
        


        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                    
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        

        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a href="../../index.html">主页</a></li>
                        
                            <li><a href="../../archives/">所有文章</a></li>
                        
                            <li><a href="../../tags/">标签云</a></li>
                        
                            <li><a href="../../about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" href="mailto:w_shixiang@163.com" title="Email"></a>
                            
                                <a class="fa GitHub" href="https://github.com/ShixiangWang" title="GitHub"></a>
                            
                                <a class="fa RSS" href="../../atom.xml" title="RSS"></a>
                            
                                <a class="fa 知乎" href="https://www.zhihu.com/people/wang-shi-xiang-65/activities" title="知乎"></a>
                            
                                <a class="fa 简书" href="https://www.jianshu.com/u/b6608e27dc74" title="简书"></a>
                            
                                <a class="fa Twitter" href="https://twitter.com/WangShxiang" title="Twitter"></a>
                            
                        </ul>
                    </nav>
                </section>
                
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="../../tags/Gist/">Gist</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/Linux-shell/">Linux shell</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/OOP/">OOP</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/R/">R</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/Rmarkdown/">Rmarkdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/Rmd/">Rmd</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/Rstudio/">Rstudio</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/bash-shell/">bash shell</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/fasta/">fasta</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/git/">git</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/github/">github</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/lapply/">lapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/linux/">linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/markdown/">markdown</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/md/">md</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/python/">python</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/sapply/">sapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/sed/">sed</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/shell笔记/">shell笔记</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/survival/">survival</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/survminer/">survminer</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/vapply/">vapply</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/写作/">写作</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/数据处理/">数据处理</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/文本处理/">文本处理</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/生存分析/">生存分析</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/生物信息学/">生物信息学</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/类/">类</a></li><li class="tag-list-item"><a class="tag-list-link" href="../../tags/迭代计算/">迭代计算</a></li></ul>
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a class="main-nav-link switch-friends-link" href="http://www.ruanyifeng.com/blog/archives.html">阮一峰的网络日志</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://blog.fens.me/series-r/">R的极客理想系列</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://yihui.name/">谢益辉</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://www.huangshujia.me/">解螺旋的矿工</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://github.com/GuangchuangYu">GuangchuangYu</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://vip.biotrainee.com/">生信技能树</a>
                    
                    </div>
                </section>
                

                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">人该是自己生活的主宰，而不是别人手中的行货</div>
                </section>
                
            </div>
        </div>
    </header>                
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">王诗翔</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                <img src="/img/avatar.png" class="animated zoomIn">
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页">王诗翔</a></h1>
            </hgroup>
            
            <p class="header-subtitle">A site for writing life</p>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="../../index.html">主页</a></li>
                
                    <li><a href="../../archives/">所有文章</a></li>
                
                    <li><a href="../../tags/">标签云</a></li>
                
                    <li><a href="../../about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" target="_blank" href="mailto:w_shixiang@163.com" title="Email"></a>
                            
                                <a class="fa GitHub" target="_blank" href="https://github.com/ShixiangWang" title="GitHub"></a>
                            
                                <a class="fa RSS" target="_blank" href="../../atom.xml" title="RSS"></a>
                            
                                <a class="fa 知乎" target="_blank" href="https://www.zhihu.com/people/wang-shi-xiang-65/activities" title="知乎"></a>
                            
                                <a class="fa 简书" target="_blank" href="https://www.jianshu.com/u/b6608e27dc74" title="简书"></a>
                            
                                <a class="fa Twitter" target="_blank" href="https://twitter.com/WangShxiang" title="Twitter"></a>
                            
                        </ul>
            </nav>
        </header>                
    </div>
    <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/>
</nav>
      <div class="body-wrap">
  
    <article id="post-shell-create-function" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/11/26/shell-create-function/" class="article-date">
      <time datetime="2017-11-25T16:00:00.000Z" itemprop="datePublished">2017-11-26</time>
</a>

 
    <a href="../../2017/11/26/shell-create-function/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/11/26/shell-create-function/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/11/26/shell-create-function/">创建和使用shell函数</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
              <p><em>来源： Linux命令行与shell脚本编程大全</em></p>
<p><strong>内容</strong></p>
<blockquote>
<ul>
<li>基本的脚本函数</li>
<li>返回值</li>
<li>在函数中使用变量</li>
<li>数组变量和函数</li>
<li>函数递归</li>
<li>创建库</li>
<li>在命令行上使用函数</li>
</ul>
</blockquote>
<p>我们可以将shell脚本代码放进函数中封装起来，这样就能在脚本中的任何地方多次使用它了。</p>
<p>下面我们来逐步了解如何创建自己的shell脚本函数并在应用中使用它们。</p>
          
      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../categories/Linux杂烩/shell编程/">shell编程</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/linux/">linux</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/shell笔记/">shell笔记</a></li></ul>
    </div>

      
        <p class="article-more-link">
          <a href="../../2017/11/26/shell-create-function/#more">阅读全文 >></a>
        </p>
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
    <article id="post-OOPinR" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/09/20/OOPinR/" class="article-date">
      <time datetime="2017-09-19T16:00:00.000Z" itemprop="datePublished">2017-09-20</time>
</a>

 
    <a href="../../2017/09/20/OOPinR/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/09/20/OOPinR/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/09/20/OOPinR/">R-面向对象编程</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
              <h2 id="一些概念"><a href="#一些概念" class="headerlink" title="一些概念"></a>一些概念</h2><p>这里首先要提及一些概念，然后我们再看具体的实例加以理解。</p>
<p>每一个单独的<strong>对象</strong>都可以被称为对应<strong>类</strong>的一个<strong>实例</strong>（instance）。操作指定类的函数称为<strong>方法</strong>（method）。</p>
<p>把程序接口从具体的实现细节中分离开来的过程称为<strong>封装</strong>。</p>
<p>在OOP（面向对象编程）中，我们可以通过一个类创建出另外一个类，只需要指定新类的不同信息即可，这种方法称为<strong>继承</strong>。由此衍生出，被继承的类称为<strong>父类或超类</strong>（superclass），新创建的类称为<strong>子类</strong>（subclass）。</p>
<p>在OOP中，允许同一个方法名操纵不同对象并得到不同的结果，称为<strong>多态</strong>（polymorphism）。</p>
<p>通过一系列的其他类来创建新类的过程称为<strong>组合</strong>（composition）。在一些语言中，一个类可以从多个类中继承方法，称为<strong>多重继承</strong>（multiple inheritance）。</p>
          
      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/极客R/">极客R</a><a class="article-category-link" href="../../categories/极客R/基本理论/">基本理论</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/OOP/">OOP</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/R/">R</a></li></ul>
    </div>

      
        <p class="article-more-link">
          <a href="../../2017/09/20/OOPinR/#more">阅读全文 >></a>
        </p>
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
    <article id="post-Class-in-R" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/09/15/Class-in-R/" class="article-date">
      <time datetime="2017-09-14T16:00:00.000Z" itemprop="datePublished">2017-09-15</time>
</a>

 
    <a href="../../2017/09/15/Class-in-R/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/09/15/Class-in-R/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/09/15/Class-in-R/">R中的属性与类</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
              <h2 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h2><p>属性描述了对象所代表的内容以及R解释该对象的方式。<strong>很多时候两个对象之间的唯一差别就在于它们的属性不同</strong>。下表展示了一些重要的属性。很多常见的属性都是针对常见的数值型数据对象而言的：像数组、矩阵和数据框。</p>
          
      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/极客R/">极客R</a><a class="article-category-link" href="../../categories/极客R/基本理论/">基本理论</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/R/">R</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/类/">类</a></li></ul>
    </div>

      
        <p class="article-more-link">
          <a href="../../2017/09/15/Class-in-R/#more">阅读全文 >></a>
        </p>
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
    <article id="post-control_shell" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/09/04/control_shell/" class="article-date">
      <time datetime="2017-09-03T16:00:00.000Z" itemprop="datePublished">2017-09-04</time>
</a>

 
    <a href="../../2017/09/04/control_shell/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/09/04/control_shell/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/09/04/control_shell/">控制脚本</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
              <blockquote>
<p><strong>内容</strong></p>
<ul>
<li>处理信号</li>
<li>以后台模式运行脚本</li>
<li>禁止挂起</li>
<li>作业控制</li>
<li>修改脚本优先级</li>
<li>脚本执行自动化</li>
</ul>
</blockquote>
          
      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../categories/Linux杂烩/shell编程/">shell编程</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/linux/">linux</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/shell笔记/">shell笔记</a></li></ul>
    </div>

      
        <p class="article-more-link">
          <a href="../../2017/09/04/control_shell/#more">阅读全文 >></a>
        </p>
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
    <article id="post-Linux-data-analysis-tools" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/09/03/Linux-data-analysis-tools/" class="article-date">
      <time datetime="2017-09-02T16:00:00.000Z" itemprop="datePublished">2017-09-03</time>
</a>

 
    <a href="../../2017/09/03/Linux-data-analysis-tools/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/09/03/Linux-data-analysis-tools/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/09/03/Linux-data-analysis-tools/">Linux数据处理命令工具</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
              <p>参考学习《Bioinformatics. Data. Skills》，这里简要地整理下Linux用来处理数据文本的工具。具体命令详情请在<a href="http://man.linuxde.net/" target="_blank" rel="noopener">Linux命令大全</a>中搜索或者查阅其他相关资料。</p>
          
      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../categories/Linux杂烩/文本处理/">文本处理</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/Linux-shell/">Linux shell</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/数据处理/">数据处理</a></li></ul>
    </div>

      
        <p class="article-more-link">
          <a href="../../2017/09/03/Linux-data-analysis-tools/#more">阅读全文 >></a>
        </p>
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
    <article id="post-shell-show-data" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/08/21/shell-show-data/" class="article-date">
      <time datetime="2017-08-20T16:00:00.000Z" itemprop="datePublished">2017-08-21</time>
</a>

 
    <a href="../../2017/08/21/shell-show-data/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/08/21/shell-show-data/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/08/21/shell-show-data/">Linux脚本编程——呈现数据</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
              <blockquote>
<p>本章内容：</p>
<ul>
<li>再探重定向</li>
<li>标准输入和输出</li>
<li>报告错误</li>
<li>丢弃数据</li>
<li>创建日志文件</li>
</ul>
</blockquote>
          
      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../categories/Linux杂烩/shell编程/">shell编程</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/bash-shell/">bash shell</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/shell笔记/">shell笔记</a></li></ul>
    </div>

      
        <p class="article-more-link">
          <a href="../../2017/08/21/shell-show-data/#more">阅读全文 >></a>
        </p>
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
    <article id="post-working-with-user-input" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/08/19/working-with-user-input/" class="article-date">
      <time datetime="2017-08-18T16:00:00.000Z" itemprop="datePublished">2017-08-19</time>
</a>

 
    <a href="../../2017/08/19/working-with-user-input/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/08/19/working-with-user-input/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/08/19/working-with-user-input/">Shell脚本之处理用户输入</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
              <p><strong>Shell脚本笔记系列：</strong></p>
<p><a href="http://www.flypeom.site/linux/2017/08/11/basic-shell/" target="_blank" rel="noopener">构建基本shell脚本</a></p>
<p><a href="http://www.flypeom.site/linux/2017/08/11/structural-command-of-shell/" target="_blank" rel="noopener">Linux结构化命令</a></p>
<blockquote>
<p>内容：</p>
<ul>
<li>传递参数</li>
<li>跟踪参数</li>
<li>移动变量</li>
<li>处理选项</li>
<li>将选项标准化</li>
<li>获得用户输入</li>
</ul>
</blockquote>
<p>经过前面的介绍，我们已经可以掌握一些流程化的脚本编程了。但有时候，我们需要编写的脚本能够跟使用者进行交互。它可以是静态的，输入相应的参数让它运行到底；也可以是动态的，脚本根据输入参数反馈不同的信息，使用者又能根据信息调整下一步的处理，实时与程序互动。</p>
<p>bash shell提供了一些不同的方法来从<strong>用户处获得数据，包括命令行参数、命令行选项以及直接从键盘读取输入</strong>的能力。下面将一一介绍实现。</p>
          
      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../categories/Linux杂烩/shell编程/">shell编程</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/bash-shell/">bash shell</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/shell笔记/">shell笔记</a></li></ul>
    </div>

      
        <p class="article-more-link">
          <a href="../../2017/08/19/working-with-user-input/#more">阅读全文 >></a>
        </p>
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
    <article id="post-structural-command-of-shell" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/08/11/structural-command-of-shell/" class="article-date">
      <time datetime="2017-08-10T16:00:00.000Z" itemprop="datePublished">2017-08-11</time>
</a>

 
    <a href="../../2017/08/11/structural-command-of-shell/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/08/11/structural-command-of-shell/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/08/11/structural-command-of-shell/">Linux结构化命令</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <a id="more"></a>
<h2 id="条件控制"><a href="#条件控制" class="headerlink" title="条件控制"></a>条件控制</h2><blockquote>
<p><strong>内容</strong></p>
<ul>
<li>使用if-then语句</li>
<li>嵌套if语句</li>
<li>test命令</li>
<li>复合条件测试</li>
<li>使用双方括号和双括号</li>
<li>case命令</li>
</ul>
</blockquote>
<p>许多程序要求对shell脚本中的命令施加一些逻辑流程控制。而某些命令会根据条件判断执行相应的命令，这样的命令通常叫做<strong>结构化命令</strong>。从概念上理解，结构化命令是shell脚本的逻辑结构，不像顺序执行shell脚本，而是有组织地执行命令以应对复杂任务需求。</p>
<h3 id="if-then语句"><a href="#if-then语句" class="headerlink" title="if-then语句"></a>if-then语句</h3><p>最基本的结构化命令是if-then语句，它的格式如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">if command</span><br><span class="line">then</span><br><span class="line">truecommands</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>
<p><strong>注意</strong>，在其他编程语言中，<code>if</code>语句之后的对象是一个等式，等式的结果为<code>TRUE</code>或者<code>FALSE</code>，但是bash shell中的<code>if</code>语句是运行<code>if</code>后面的命令，如果该命令的退出状态码是0（命令成功执行），则运行<code>then</code>语句后面的命令。<code>fi</code>表示<code>if</code>语句到此结束。</p>
<p>下面是一个简单的例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test1.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">! /bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> testing the <span class="keyword">if</span> statement</span></span><br><span class="line">if pwd</span><br><span class="line">then</span><br><span class="line">    echo "It worked"</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test1.sh</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1.sh</span><br><span class="line">/home/wsx/script_learn</span><br><span class="line">It worked</span><br></pre></td></tr></table></figure>
<p>这个例子中在判断成功执行<code>pwd</code>命令后，执行输出文本字符串。</p>
<p>大家可以尝试把<code>pwd</code>命令改成随便乱打的字符试试结果。它会显示报错信息，<code>then</code>后面的语句也不会执行。</p>
<p>if-then语句的另一种形式：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if command; then</span><br><span class="line">commands</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>
<p>在then部分，我们可以使用多个命令（从格式中command结尾有没有s也可以看出）。</p>
<p>我们再来一个例子：在<code>if</code>语句中用<code>grep</code>命令在<code>/etc/passwd</code>文件中查找某个用户名当前是否在系统上使用。如果有用户使用了哪个登录名，脚本会显示一些文本信息并列出该用户HOME目录的bash文件。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test3.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> testing multiple commands <span class="keyword">in</span> the <span class="keyword">then</span> section</span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">testuser=wsx</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">if grep $testuser /etc/passwd</span><br><span class="line">then</span><br><span class="line">  echo "This is my first command"</span><br><span class="line">  echo "This is my second command"</span><br><span class="line">  echo "I can even put in other commands besides echo:"</span><br><span class="line">  ls -a /home/$testuser/.b*</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test3.sh</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test3.sh</span><br><span class="line">wsx:x:1000:1000:wsx,,,:/home/wsx:/bin/bash</span><br><span class="line">This is my first command</span><br><span class="line">This is my second command</span><br><span class="line">I can even put in other commands besides echo:</span><br><span class="line">/home/wsx/.bash_history  /home/wsx/.bashrc</span><br><span class="line">/home/wsx/.bash_logout	 /home/wsx/.bashrc-anaconda3.bak</span><br></pre></td></tr></table></figure>
<p>如果设置的用户名不存在，那么就没有输出。那么如果在这里显示的一些消息可以说明用户名在系统中未找到，这样可能就会显得更友好。所以接下来看看<code>if-then-else</code>语句。</p>
<h3 id="if-then-else语句"><a href="#if-then-else语句" class="headerlink" title="if-then-else语句"></a>if-then-else语句</h3><p>我相信意思非常容易理解，这里较之前我们添加了一个<code>else</code>块来处理<code>if</code>中命令没有成功执行的步骤。格式为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">if command</span><br><span class="line">then</span><br><span class="line">  commands</span><br><span class="line">else commands</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>
<h3 id="嵌套if"><a href="#嵌套if" class="headerlink" title="嵌套if"></a>嵌套if</h3><p>有时我们需要检查脚本代码中的多种条件，可以是用嵌套的<code>if-then</code>语句。</p>
<p>处理一个例子：检查<code>/etc/passwd</code>文件中是否存在某个用户名以及该用户名的目录是否存在。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test5.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> Testing nested ifs</span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">testuser=NoSuchUser</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">if grep $testuser /etc/passwd</span><br><span class="line">then</span><br><span class="line">  echo "The user $testuser exits on this system."</span><br><span class="line">else</span><br><span class="line">  echo "The user $testuser does not exit on this system."</span><br><span class="line">  if ls -d /home/$testuser/</span><br><span class="line">  then</span><br><span class="line">     echo "However, $testuser has a directory."</span><br><span class="line">  fi</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test5.sh</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test5.sh</span><br><span class="line">The user NoSuchUser does not exit on this system.</span><br><span class="line">ls: 无法访问'/home/NoSuchUser/': 没有那个文件或目录</span><br></pre></td></tr></table></figure>
<p>可以使用<code>else</code>部分的另一种形式:<code>elif</code>。这样我们就不再用书写多个<code>if-then</code>语句了。在其他语言中，有的是用<code>elif</code>的形式，有的使用<code>else if</code>等形式。面对相同内含在不同语言中不同的表示方式，我们需要有意识地区别，以免接触的东西多了可能各种语言代码串写喔。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">if command1</span><br><span class="line">then</span><br><span class="line">truecommands</span><br><span class="line">elif command2</span><br><span class="line">then</span><br><span class="line">truemore commands</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>
<p>这种表示方式逻辑更为清晰，但是也有点容易让写的人搞混。其实可以看到一个<code>if</code>对应一个<code>fi</code>。这是一个大的嵌套<code>if</code>结构。</p>
<p><strong>记住</strong>，在<code>elif</code>语句中，紧跟其后的<code>else</code>语句属于<code>elif</code>代码块，而不是属于<code>if-then</code>代码块。</p>
<h3 id="test命令"><a href="#test命令" class="headerlink" title="test命令"></a>test命令</h3><p>到此为止，我们很清楚<code>if</code>后面跟着的是普通的shell命令，那么我们需要测试其他条件怎么办呢？</p>
<p><code>test</code>命令提供了在<code>if-then</code>语句中测试不同条件的途径。如果<code>test</code>命令中列出的条件成立，<code>test</code>命令就会退出并返回状态码0。这样<code>if-then</code>语句就与其他编程语言中的<code>if-then</code>语句以类似的方式工作了。</p>
<p>test命令格式：</p>
<figure class="highlight subunit"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">test </span>condition</span><br></pre></td></tr></table></figure>
<p><code>condition</code>是<code>test</code>命令要测试的一系列参数和值。如果不写这个<code>condition</code>，<code>test</code>返回非0，<code>if</code>语句跳转到<code>else</code>进行执行。</p>
<p>bash shell提供了一种条件测试方法，无需在<code>if-then</code>语句中声明<code>test</code>命令。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if [ condition ]</span><br><span class="line">then commands</span><br><span class="line">fi</span><br></pre></td></tr></table></figure>
<p>这跟我们其他的编程习惯非常接近。建议使用这种方式。</p>
<p>如果使用<code>test</code>命令，需要记住的是各种条件参数。</p>
<p><strong>数值比较</strong></p>
<table>
<thead>
<tr>
<th>比较</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>n1 -eq n2</td>
<td>(n1)等于(n2)</td>
</tr>
<tr>
<td>n1 -ge n2</td>
<td>大于或等于</td>
</tr>
<tr>
<td>n1 -gt n2</td>
<td>大于</td>
</tr>
<tr>
<td>n1 -le n2</td>
<td>小于或等于</td>
</tr>
<tr>
<td>n1 -lt n2</td>
<td>小于</td>
</tr>
<tr>
<td>n1 -ne n2</td>
<td>不等于</td>
</tr>
</tbody>
</table>
<p><strong>字符串比较</strong></p>
<table>
<thead>
<tr>
<th>比较</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>str1 = str2</td>
<td>（str1与str2比较）相同</td>
</tr>
<tr>
<td>str1 != str2</td>
<td>不同</td>
</tr>
<tr>
<td>str1 &lt; str2</td>
<td>小</td>
</tr>
<tr>
<td>str1 &gt; str2</td>
<td>大</td>
</tr>
<tr>
<td>-n str1</td>
<td>检查string1的长度非0</td>
</tr>
<tr>
<td>-z str1</td>
<td>检查string1的长度是否为0</td>
</tr>
</tbody>
</table>
<p>注意，大于和小于号必须转义；大于和小于顺序和sort命令所采用的不同。</p>
<p><strong>文件比较</strong></p>
<table>
<thead>
<tr>
<th>比较</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>-d file</td>
<td>检查file是否存在并是一个目录</td>
</tr>
<tr>
<td>-e file</td>
<td>～是否存在</td>
</tr>
<tr>
<td>-f file</td>
<td>～是否存在并是一个文件</td>
</tr>
<tr>
<td>-r file</td>
<td>～是否存在并可读</td>
</tr>
<tr>
<td>-s file</td>
<td>～是否存在并非空</td>
</tr>
<tr>
<td>-w file</td>
<td>～是否存在并可写</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>-x file</td>
<td>～是否存在并可执行</td>
</tr>
<tr>
<td>-O file</td>
<td>～是否存在并属当前用户所有</td>
</tr>
<tr>
<td>-G file</td>
<td>～是否存在并且默认组与当前用户相同</td>
</tr>
<tr>
<td>file1 -nt file2</td>
<td>检查file1是否比file2新</td>
</tr>
<tr>
<td>file1 -ot file2</td>
<td>检查file1是否比file2旧</td>
</tr>
</tbody>
</table>
<h3 id="复合条件测试"><a href="#复合条件测试" class="headerlink" title="复合条件测试"></a>复合条件测试</h3><p><code>if-then</code>语句允许我们使用布尔逻辑来组合测试。可用</p>
<ul>
<li>[ condition1] &amp;&amp; [ condition2]</li>
<li><code>[ condition1] || [ condition2]</code></li>
</ul>
<h3 id="if-then的高级特性"><a href="#if-then的高级特性" class="headerlink" title="if-then的高级特性"></a>if-then的高级特性</h3><ul>
<li>用于数学表达式的双括号</li>
<li>用于高级字符串处理功能的双方括号</li>
</ul>
<p><strong>双括号</strong></p>
<p>命令格式：</p>
<figure class="highlight lisp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(( <span class="name">expresiion</span> ))</span><br></pre></td></tr></table></figure>
<p><code>expression</code>可以是任意的数学赋值或比较表达式。除了<code>test</code>命令使用的标准数学运算符，下面列出了一些其他的：</p>
<table>
<thead>
<tr>
<th>符号</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>val ++</td>
<td>后增</td>
</tr>
<tr>
<td>val –</td>
<td>后减</td>
</tr>
<tr>
<td>++ val</td>
<td>先增</td>
</tr>
<tr>
<td>– val</td>
<td>先减</td>
</tr>
<tr>
<td>!</td>
<td>逻辑取反</td>
</tr>
<tr>
<td>~</td>
<td>位求反</td>
</tr>
<tr>
<td>**</td>
<td>幂运算</td>
</tr>
<tr>
<td>&lt;&lt;</td>
<td>左位移</td>
</tr>
<tr>
<td>&gt;&gt;</td>
<td>右位移</td>
</tr>
<tr>
<td>&amp;</td>
<td>位布尔和</td>
</tr>
<tr>
<td>\</td>
<td></td>
<td>位布尔或</td>
</tr>
<tr>
<td>&amp;&amp;</td>
<td>逻辑和</td>
</tr>
<tr>
<td>\</td>
<td>\</td>
<td></td>
<td>逻辑或</td>
</tr>
</tbody>
</table>
<p>看一个例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test23.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> using doble parenthesis</span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">val1=10</span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">if (( $val1 ** 2 &gt; 90 ))</span><br><span class="line">then</span><br><span class="line">  (( val2 = $val1 ** 2 ))</span><br><span class="line">  echo "The square of $val1 is $val2"</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test23.sh</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test23.sh</span><br><span class="line">The square of 10 is 100</span><br></pre></td></tr></table></figure>
<p><strong>双方括号</strong></p>
<p>双方括号命令提供了针对字符串比较的高级特性。命令格式如下：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">[[ expression ]]</span></span><br></pre></td></tr></table></figure>
<p>双方括号里的<code>expression</code>使用了<code>test</code>命令中采用的标准字符串比较。但它提供了<code>test</code>没有提供的一个特性——模式匹配。</p>
<p>在模式匹配中，可以定义一个正则表达式来匹配字符串值。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test24.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">! /bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> using pattern matching</span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">if [[ $USER == r* ]]</span><br><span class="line">then</span><br><span class="line">  echo "Hello $USER"</span><br><span class="line">else</span><br><span class="line">  echo "Sorry, I do not know you"</span><br><span class="line">fi</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test24.sh</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test24.sh</span><br><span class="line">Sorry, I do not know you</span><br></pre></td></tr></table></figure>
<p>上面一个脚本中，我们使用了双等号。双等号将右边的字符串视为一个模式，并将其应用模式匹配规则。</p>
<h3 id="case命令"><a href="#case命令" class="headerlink" title="case命令"></a>case命令</h3><p>有了<code>case</code>命令，就不需要写出所有的<code>elif</code>语句来不停地检查同一个变量的值了。<code>case</code>命令会采用列表格式来检查单个变量的多值。</p>
<p>下面是两个脚本实现相同功能进行对比：</p>
<p>if语句：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test25.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> looking <span class="keyword">for</span> a possible value</span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">if [ $USER = "rich" ]</span><br><span class="line">then</span><br><span class="line">  echo "Welcome $USER"</span><br><span class="line">  echo "Please enjoy you visit"</span><br><span class="line">elif [ $USER = "barbara" ]</span><br><span class="line">then</span><br><span class="line">  echo "Welcome $USER"</span><br><span class="line">  echo "Please enjoy you visit"</span><br><span class="line">elif [ $USER = "testing" ]</span><br><span class="line">then</span><br><span class="line">  echo "Special testing account"</span><br><span class="line">elif [ $USER = "jessica" ]</span><br><span class="line">then</span><br><span class="line">  echo "Do not forget to logout when you're done"</span><br></pre></td></tr></table></figure>
<p>case语句：</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">case variable <span class="keyword">in</span></span><br><span class="line">pattern1 | pattern2) commands1;;</span><br><span class="line">pattern3) commands2;;</span><br><span class="line">*)<span class="built_in"> default </span>commands;;</span><br><span class="line">esac</span><br></pre></td></tr></table></figure>
<p>上面的实例可以用<code>case</code>语句表示为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test26.sh</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> using the <span class="keyword">case</span> <span class="built_in">command</span></span></span><br><span class="line"><span class="meta">#</span><span class="bash"></span></span><br><span class="line">case $USER in</span><br><span class="line">rich | barbara)</span><br><span class="line">  echo "Welcome, $USER"</span><br><span class="line">  echo "Please enjoy your visits";;</span><br><span class="line">testing)</span><br><span class="line">  echo "Special testing account";;</span><br><span class="line">jessica)</span><br><span class="line">  echo "Do not forget to log off whe you're done";;</span><br><span class="line">*)</span><br><span class="line">  echo "Sorry, you are not allowed here";;</span><br><span class="line">esac</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test26.sh</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test26.sh</span><br><span class="line">Sorry, you are not allowed here</span><br></pre></td></tr></table></figure>
<p><code>case</code>命令会将指定的变量与不同模式进行比较。如果变量和模式是匹配的，那么shell会执行为该模式指定的命令。可以通过竖线操作符在一行中分隔出多个模式。星号会捕获所有与已知模式不匹配的值。注意双分号的使用。</p>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><blockquote>
<p>最基本的命令是<code>if-then</code>语句；</p>
<p>可以拓展<code>if-then</code>语句为<code>if-then-else</code>语句；</p>
<p>可以将<code>if-then-else</code>语句通过<code>elif</code>语句连接起来；</p>
<p>在脚本中，我们需要测试一种条件而不是命令时，比如数值、字符串内容、文件或目录的状态，<code>test</code>命令提供了简单方法；</p>
<p>方括号是<code>test</code>命令统一的特殊bash命令；</p>
<p>双括号使用另一种操作符进行高级数学运算双方括号允许高级字符串模式匹配运算；</p>
<p><code>case</code>命令是执行多个<code>if-then-else</code>命令的简便方式，它会参照一个值列表来检查单个变量的值。</p>
</blockquote>
<p>关于结构化命令中循环，将在下次整理的笔记中阐述。</p>
<h2 id="循环控制"><a href="#循环控制" class="headerlink" title="循环控制"></a>循环控制</h2><blockquote>
<p><strong>内容</strong></p>
<ul>
<li>for循环语句</li>
<li>until迭代语句使用while语句</li>
<li>循环</li>
<li>重定向循环的输出</li>
</ul>
</blockquote>
<p>这一节我们来了解如何重复一些过程和命令，也就是循环执行一组命令直到达到了某个特定条件。</p>
<h3 id="for命令"><a href="#for命令" class="headerlink" title="for命令"></a>for命令</h3><p>基本格式：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">for var in list</span><br><span class="line">do</span><br><span class="line">truecommands</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<p>也可以</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">for var in list; do</span><br></pre></td></tr></table></figure>
<p>分号只用来分隔命令的，让代码更简约。</p>
<p>来个简单例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test1</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> basic <span class="keyword">for</span> <span class="built_in">command</span></span></span><br><span class="line"></span><br><span class="line">for test in Alabama Alaska Arizona Arkansas California Colorado</span><br><span class="line">do</span><br><span class="line">    echo The next state is $test</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1</span><br><span class="line">The next state is Alabama</span><br><span class="line">The next state is Alaska</span><br><span class="line">The next state is Arizona</span><br><span class="line">The next state is Arkansas</span><br><span class="line">The next state is California</span><br><span class="line">The next state is Colorado</span><br></pre></td></tr></table></figure>
<p>这里操作基本和其他语言一致（格式不同），不多讲啦。</p>
<p><strong>在读取列表中的复杂值时</strong>，我们可能会遇到问题。比如下面这个例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat badtest1</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> another example of how not to use the <span class="keyword">for</span> <span class="built_in">command</span></span></span><br><span class="line"></span><br><span class="line">for test in I don't know if this'll work</span><br><span class="line">do</span><br><span class="line">    echo "word:$test"</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./badtest1</span><br><span class="line">word:I</span><br><span class="line">word:dont know if thisll</span><br><span class="line">word:work</span><br></pre></td></tr></table></figure>
<p>我们可以看到shell看到了列表值中的单引号尝试使用它们来定义一个单独的数据值。</p>
<p>这里有两种解决办法：</p>
<ul>
<li>使用转义字符将单引号转义</li>
<li>使用双引号来定义用到单引号的值</li>
</ul>
<p>我们将这两种解决办法同时用到上个例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test2</span><br><span class="line"><span class="meta">#</span><span class="bash">! /bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> another example of how not to use the <span class="keyword">for</span> <span class="built_in">command</span></span></span><br><span class="line"></span><br><span class="line">for test in I don\'t know if "this'll" work; do</span><br><span class="line">echo  "word:$test"</span><br><span class="line">done</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test2</span><br><span class="line">word:I</span><br><span class="line">word:don't</span><br><span class="line">word:know</span><br><span class="line">word:if</span><br><span class="line">word:this'll</span><br><span class="line">word:work</span><br></pre></td></tr></table></figure>
<p>我们可能明白了<code>for</code>循环是假定每个值是用空格分隔的，所以当有包含空格的数据时，我们需要用双引号括起来。</p>
<p><strong>通常我们会将列表值存储在一个变量中</strong>，然后通过遍历变量的方式遍历了其内容的的列表。</p>
<p>看看怎么完成这个任务：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test3</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> using a variable to hold the list</span></span><br><span class="line">list="Alabama Alaska Arizona Arkansas Colorado"</span><br><span class="line">list=$list" Connecticut" # 在尾部拼接文本</span><br><span class="line"></span><br><span class="line">for state in $list; do</span><br><span class="line">  echo "Have you ever visited $state?"</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test3</span><br><span class="line">Have you ever visited Alabama?</span><br><span class="line">Have you ever visited Alaska?</span><br><span class="line">Have you ever visited Arizona?</span><br><span class="line">Have you ever visited Arkansas?</span><br><span class="line">Have you ever visited Colorado?</span><br><span class="line">Have you ever visited Connecticut?</span><br></pre></td></tr></table></figure>
<p>注意，代码中还用了另一个赋值语句向<code>$list</code>变量包含的已有列表中添加了一个值。这是在已有文本字符串尾部添加文本的一种常用方法。</p>
<p>我们还可以<strong>用命令来输出我们需要的列表内容</strong>：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test4</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> reading values from a file</span></span><br><span class="line"></span><br><span class="line">file="states"</span><br><span class="line"></span><br><span class="line">for state in $(cat $file)</span><br><span class="line">do</span><br><span class="line">    echo "Visit beautiful $state"</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat states</span><br><span class="line">Alabama</span><br><span class="line">Alaska</span><br><span class="line">Arizona</span><br><span class="line">Arkansas</span><br><span class="line">Colorado</span><br><span class="line">Connecticut</span><br><span class="line">Delaware</span><br><span class="line">Florida</span><br><span class="line">Georgia</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test4</span><br><span class="line">Visit beautiful Alabama</span><br><span class="line">Visit beautiful Alaska</span><br><span class="line">Visit beautiful Arizona</span><br><span class="line">Visit beautiful Arkansas</span><br><span class="line">Visit beautiful Colorado</span><br><span class="line">Visit beautiful Connecticut</span><br><span class="line">Visit beautiful Delaware</span><br><span class="line">Visit beautiful Florida</span><br><span class="line">Visit beautiful Georgia</span><br></pre></td></tr></table></figure>
<p><strong>更改字段分隔符</strong></p>
<p>环境变量<code>IFS</code>，也叫作字段分隔符。它定义了bash shell用作字段分隔符的一系列字符。默认情况下，bash shell会将<strong>空格、制表符和换行符</strong>当作字段分隔符。</p>
<p>如果想修改<code>IFS</code>的值，比如使其只能识别换行符，我们可以将下面这行代码加入脚本：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IFS=$'\n'</span><br></pre></td></tr></table></figure>
<p>在处理大量脚本时，我们可能只在某一部分使用其他的分隔符，这时候可以先保存原有的<code>IFS</code>值，然后修改，最后恢复：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">IFS.OLD=$IFS</span><br><span class="line">IFS=$'\n'</span><br><span class="line">&lt;在代码中使用新的IFS值&gt;</span><br><span class="line">IFS=$IFS.OLD</span><br></pre></td></tr></table></figure>
<p>假如我们要遍历一个文件中用冒号分隔的值：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IFS=:</span><br></pre></td></tr></table></figure>
<p>假如要指定多个<code>IFS</code>字符，只要将它们的赋值行串起来：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">IFS=$'\n':;"</span><br></pre></td></tr></table></figure>
<p>这个赋值会将换行符、冒号、分号以及双引号作为字段分隔符。</p>
<p><strong>用通配符读取目录</strong></p>
<p>我们可以用<code>for</code>命令来自动遍历目录中的文件。进行此操作时，必须在文件名或路径名中使用通配符。它会强制shell使用<strong>文件扩展匹配</strong>。文件扩展匹配是生成匹配指定通配符的文件名或路径名的过程。</p>
<p>我拿我的一个目录来尝试一下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test5</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> iterate through all the files <span class="keyword">in</span> a directory</span></span><br><span class="line"></span><br><span class="line">for file in /home/wsx/python_learn/*</span><br><span class="line">do</span><br><span class="line">  if [ -d "$file" ]</span><br><span class="line">  then</span><br><span class="line">    echo "$file is a directory"</span><br><span class="line">  elif [ -f "$file" ]</span><br><span class="line">  then</span><br><span class="line">    echo "$file is a file"</span><br><span class="line">  fi</span><br><span class="line">done</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test5</span><br><span class="line">/home/wsx/python_learn/athletelist.py is a file</span><br><span class="line">/home/wsx/python_learn/athletemodel.py is a file</span><br><span class="line">/home/wsx/python_learn/ch2_data_input.py is a file</span><br><span class="line">/home/wsx/python_learn/chapter5_first.py is a file</span><br><span class="line">/home/wsx/python_learn/chapter6_first.py is a file</span><br><span class="line">/home/wsx/python_learn/chapter6_second.py is a file</span><br><span class="line">/home/wsx/python_learn/chapter6_third.py is a file</span><br><span class="line">/home/wsx/python_learn/coinFlips.py is a file</span><br><span class="line">/home/wsx/python_learn/Dive_into_python is a directory</span><br></pre></td></tr></table></figure>
<p><strong>注意：</strong>第一个方括号之后和第二个方括号之前必须加上一个空格，否则会报错。</p>
<p>在Linux中，目录名和文件名中包含空格是合法的，所以将<code>$file</code>变量用双引号圈起来。当然，大家尽量不要让文件或目录包含空格，不然很容易出问题（命令会把空格当做文件的分隔符）。</p>
<h3 id="C语言风格的for命令"><a href="#C语言风格的for命令" class="headerlink" title="C语言风格的for命令"></a>C语言风格的for命令</h3><p>C语言风格的<code>for</code>命令看起来如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">for (( a = 1; a &lt; 10; a++ ))</span><br></pre></td></tr></table></figure>
<p>值得注意的是，这里有些部分没有遵循bash shell标准的<code>for</code>命令：</p>
<ul>
<li>变量赋值可以有空格；</li>
<li>条件中的变量不以美元符开头；</li>
<li>迭代过程的算式未用<code>expr</code>命令格式。</li>
</ul>
<p>在使用这种格式时要小心，不同的格式不注意就会出错。</p>
<p>下面举个例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test6</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> testing the C-style <span class="keyword">for</span> loop</span></span><br><span class="line"></span><br><span class="line">for (( i=1; i &lt;= 10; i++ ))</span><br><span class="line">do</span><br><span class="line">  echo "The next number is $i"</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test6</span><br><span class="line">The next number is 1</span><br><span class="line">The next number is 2</span><br><span class="line">The next number is 3</span><br><span class="line">The next number is 4</span><br><span class="line">The next number is 5</span><br><span class="line">The next number is 6</span><br><span class="line">The next number is 7</span><br><span class="line">The next number is 8</span><br><span class="line">The next number is 9</span><br><span class="line">The next number is 10</span><br></pre></td></tr></table></figure>
<h3 id="while命令"><a href="#while命令" class="headerlink" title="while命令"></a>while命令</h3><p><code>while</code>命令的格式为：<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">while test command</span><br><span class="line">do</span><br><span class="line">  other commands</span><br><span class="line">done</span><br></pre></td></tr></table></figure></p>
<p><code>while</code>命令某种意义上是<code>if-then</code>语句和<code>for</code>循环的混杂体。注意，这里<code>while</code>后面接的也是命令。<code>while</code>命令允许定义一个要测试的命令，然后循环执行一组命令，只要定义的测试命令返回的是退出状态码是0（类似一般语言中 的TRUE）。直到非0时退出循环。</p>
<p><code>while</code>命令中定义的<code>test command</code>和<code>if-then</code>语句中的格式一模一样。可以使用任何普通的bash shell命令，或者用<code>test</code>命令进行条件测试，比如测试变量值。</p>
<p>最常见的用法是用方括号来检查循环命令中用到的<code>shell</code>变量的值。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test</span><br><span class="line"><span class="meta">#</span><span class="bash">/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> <span class="keyword">while</span> <span class="built_in">command</span> <span class="built_in">test</span></span></span><br><span class="line"></span><br><span class="line">var1=10</span><br><span class="line">while [ $var1 -gt 0 ]</span><br><span class="line">do</span><br><span class="line">        echo $var1</span><br><span class="line">        var1=$[ $var1 - 1 ]</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ ./test</span><br><span class="line">10</span><br><span class="line">9</span><br><span class="line">8</span><br><span class="line">7</span><br><span class="line">6</span><br><span class="line">5</span><br><span class="line">4</span><br><span class="line">3</span><br><span class="line">2</span><br><span class="line">1</span><br></pre></td></tr></table></figure>
<p><strong>使用多个测试命令</strong><br><code>while</code>命令允许我们在<code>while</code>语句行中定义多个测试命令。只有最后一个测试命令的退出状态码会被用来决定什么时候结束循环。<br>比如<code>while echo $var1 [ $var1 -ge 0 ]</code>检测的就是后面方括号命令的退出状态码。</p>
<h3 id="until命令"><a href="#until命令" class="headerlink" title="until命令"></a>until命令</h3><p><code>until</code>命令和<code>while</code>命令工作的方式完全相反。只有测试命令的退出状态码不为0，bash shell才会执行循环中列出的命令。一旦测试命令返回了退出状态码0，循环就结束了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">until test command</span><br><span class="line">do</span><br><span class="line">  other commands</span><br><span class="line">done</span><br></pre></td></tr></table></figure>
<p>一个例子：<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test12</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> using the until <span class="built_in">command</span></span></span><br><span class="line"></span><br><span class="line">var1=100</span><br><span class="line"></span><br><span class="line">until [ $var1 -eq 0 ]</span><br><span class="line">do</span><br><span class="line">        echo $var1</span><br><span class="line">        var1=$[ $var1 - 25 ]</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ ./test12</span><br><span class="line">100</span><br><span class="line">75</span><br><span class="line">50</span><br><span class="line">25</span><br></pre></td></tr></table></figure></p>
<p>同样地，在<code>until</code>命令中放入多个测试命令时也要注意（类似<code>while</code>）。</p>
<h3 id="嵌套循环"><a href="#嵌套循环" class="headerlink" title="嵌套循环"></a>嵌套循环</h3><p>在循环语句内使用任意类型的命令，包括其他循环命令，叫做嵌套循环。因为是在迭代中迭代，需要注意变量的使用以及程序的效率问题。</p>
<p>下面举一个<code>for</code>循环嵌套<code>for</code>循环的例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test14</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> nesting <span class="keyword">for</span> loops</span></span><br><span class="line"></span><br><span class="line">for (( a = 1; a &lt;= 3; a++ ))</span><br><span class="line">do</span><br><span class="line">        echo "Starting loop $a:"</span><br><span class="line">        for (( b = 1; b &lt;= 3; b++ ))</span><br><span class="line">        do</span><br><span class="line">                echo "    Inside loop: $b"</span><br><span class="line">        done</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ . test14</span><br><span class="line">Starting loop 1:</span><br><span class="line">    Inside loop: 1</span><br><span class="line">    Inside loop: 2</span><br><span class="line">    Inside loop: 3</span><br><span class="line">Starting loop 2:</span><br><span class="line">    Inside loop: 1</span><br><span class="line">    Inside loop: 2</span><br><span class="line">    Inside loop: 3</span><br><span class="line">Starting loop 3:</span><br><span class="line">    Inside loop: 1</span><br><span class="line">    Inside loop: 2</span><br><span class="line">    Inside loop: 3</span><br></pre></td></tr></table></figure>
<p>shell能够自动识别匹配的<code>do</code>和<code>done</code>字符。这种模式很常见，比如通常的小括号（<code>(</code>与<code>)</code>）、中括号、花括号匹配等等。它们的本质都是字符匹配。</p>
<p>在混用循环命令时也一样，比如在<code>while</code>循环中内嵌一个<code>for</code>循环：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test15</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> placing a <span class="keyword">for</span> loop inside a <span class="keyword">while</span> loop</span></span><br><span class="line"></span><br><span class="line">var1=5</span><br><span class="line"></span><br><span class="line">while [ $var1 -ge 0 ]</span><br><span class="line">do</span><br><span class="line">        echo "Outer loop: $var1"</span><br><span class="line">        for (( var2 = 1; $var2 &lt; 3; var2++))</span><br><span class="line">        do</span><br><span class="line">                var3=$[ $var1 * $var2 ]</span><br><span class="line">                echo "  Inner loop: $var1 * $var2 = $var3"</span><br><span class="line">        done</span><br><span class="line">        var1=$[ $var1 - 1 ]</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ . test15</span><br><span class="line">Outer loop: 5</span><br><span class="line">  Inner loop: 5 * 1 = 5</span><br><span class="line">  Inner loop: 5 * 2 = 10</span><br><span class="line">Outer loop: 4</span><br><span class="line">  Inner loop: 4 * 1 = 4</span><br><span class="line">  Inner loop: 4 * 2 = 8</span><br><span class="line">Outer loop: 3</span><br><span class="line">  Inner loop: 3 * 1 = 3</span><br><span class="line">  Inner loop: 3 * 2 = 6</span><br><span class="line">Outer loop: 2</span><br><span class="line">  Inner loop: 2 * 1 = 2</span><br><span class="line">  Inner loop: 2 * 2 = 4</span><br><span class="line">Outer loop: 1</span><br><span class="line">  Inner loop: 1 * 1 = 1</span><br><span class="line">  Inner loop: 1 * 2 = 2</span><br><span class="line">Outer loop: 0</span><br><span class="line">  Inner loop: 0 * 1 = 0</span><br><span class="line">  Inner loop: 0 * 2 = 0</span><br></pre></td></tr></table></figure>
<p>如果想要挑战脑力，可以混用<code>until</code>和<code>while</code>循环。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test16</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> using until and <span class="keyword">while</span> loop</span></span><br><span class="line"></span><br><span class="line">var1=3</span><br><span class="line"></span><br><span class="line">until [ $var1 -eq 0 ]</span><br><span class="line">do</span><br><span class="line">        echo "Outer loop: $var1"</span><br><span class="line">        var2=1</span><br><span class="line">        while [ $var2 -lt 5 ]</span><br><span class="line">        do</span><br><span class="line">                var3=$(echo "scale=4; $var1 / $var2" | bc)</span><br><span class="line">                echo "  Inner loop: $var1 / $var2 = $var3"</span><br><span class="line">                var2=$[ $var2 + 1 ]</span><br><span class="line">        done</span><br><span class="line">        var1=$[ $var1 - 1 ]</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">wangsx@SC-201708020022:~/tmp$ . test16</span><br><span class="line">Outer loop: 3</span><br><span class="line">  Inner loop: 3 / 1 = 3.0000</span><br><span class="line">  Inner loop: 3 / 2 = 1.5000</span><br><span class="line">  Inner loop: 3 / 3 = 1.0000</span><br><span class="line">  Inner loop: 3 / 4 = .7500</span><br><span class="line">Outer loop: 2</span><br><span class="line">  Inner loop: 2 / 1 = 2.0000</span><br><span class="line">  Inner loop: 2 / 2 = 1.0000</span><br><span class="line">  Inner loop: 2 / 3 = .6666</span><br><span class="line">  Inner loop: 2 / 4 = .5000</span><br><span class="line">Outer loop: 1</span><br><span class="line">  Inner loop: 1 / 1 = 1.0000</span><br><span class="line">  Inner loop: 1 / 2 = .5000</span><br><span class="line">  Inner loop: 1 / 3 = .3333</span><br><span class="line">  Inner loop: 1 / 4 = .2500</span><br></pre></td></tr></table></figure>
<p>外部的<code>until</code>循环以值3开始，并继续执行到值等于0。内部<code>while</code>循环以值1开始一直执行，只要值小于5。需要注意循环条件的设置，我跑的几次都没写完整，然后无限循环只好重开终端。</p>
<h3 id="控制循环"><a href="#控制循环" class="headerlink" title="控制循环"></a>控制循环</h3><p>之前的学的命令已经可以让我们写循环程序了，设定好以后等待命令开始执行和等待循环结束。但是很多情况下，在循环中我们设定的某个（多个）变量达到某种条件时，我们就想要停止循环，然后运行循环下面的命令。这时候我们需要用到<code>break</code>和<code>continue</code>命令来帮我们控制住循环。</p>
<p>这两个命令在其他语言中基本都时关键字，特别是<code>C</code>，用法差不多。我也就不具体介绍了，只点出它们的功能。</p>
<p><strong>break</strong></p>
<blockquote>
<p>在shell执行break命令时，它会尝试跳出当前正在执行的循环。</p>
<p>在处理多个循环时，break命令会自动终止你所在的最内层循环。</p>
<p>break命令接受单个命令行参数值：</p>
<p>​    break n</p>
<p>​    其中n制订了要跳出的循环层级（层数）</p>
</blockquote>
<p><strong>continue</strong></p>
<blockquote>
<p>continue命令可以提前终止某次循环的命令，但并不会完全终止整个循环。可以在循环内部设置shell不执行命令的条件。</p>
<p>也就是说使用continue命令时，它会自动跳过本次循环中接下来的运行步骤，跳转到下一次循环。但注意不是跳出，跳出时break的功能。</p>
<p>同样的可以使用continue n         n制定要继续执行哪一级循环</p>
</blockquote>
<h3 id="处理循环的输出"><a href="#处理循环的输出" class="headerlink" title="处理循环的输出"></a>处理循环的输出</h3><p>在shell脚本中，我们可以对循环的输出使用管道或进行重定向。这是通过在<code>done</code>命令之后添加一个处理命令来实现的。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~/tmp$ cat test</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line">for file in /home/*</span><br><span class="line">do</span><br><span class="line">        if [ -d "$file" ]</span><br><span class="line">        then</span><br><span class="line">                echo "$file is a directory"</span><br><span class="line">        else</span><br><span class="line">                echo "$file is a file"</span><br><span class="line">        fi</span><br><span class="line">done &gt; output.txt</span><br><span class="line">wangsx@SC-201708020022:~/tmp$ cat output.txt</span><br><span class="line">/home/wangsx is a directory</span><br></pre></td></tr></table></figure>
<p>shell将<code>for</code>命令的结果重定向到文件<code>output.txt</code>中，而不是显示在屏幕上。</p>
<h3 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h3><p>下面两个例子演示如何用简单循环来处理数据。</p>
<p><strong>查找可执行文件</strong></p>
<p>Linux运行程序时通过环境变量<code>$PATH</code>提供的目录搜索可执行文件。如果徒手找的话，比较费时间，我们可以写个脚本来搞定它。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">wangsx@SC-201708020022:~$ cat test25</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> finding files <span class="keyword">in</span> the PATH</span></span><br><span class="line"></span><br><span class="line">IFS=:</span><br><span class="line">for folder in $PATH</span><br><span class="line">do</span><br><span class="line">        echo "$folder:"</span><br><span class="line">        for file in $folder/*</span><br><span class="line">        do</span><br><span class="line">                if [ -x $file ]</span><br><span class="line">                then</span><br><span class="line">                        echo "  $file"</span><br><span class="line">                fi</span><br><span class="line">        done</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> 输出结果太多，我就不拷贝结果了</span></span><br></pre></td></tr></table></figure>
<p>先设定<code>IFS</code>分隔符以便于能正确分隔目录，然后将目录存放在<code>$folder</code>中，用<code>for</code>循环来迭代特定的目录中所有文件，然后用<code>if-then</code>命令检查文件的可执行权限。</p>
<p>Linux有一个<code>tree</code>工具，非常方便输出目录结构，推荐使用下。</p>
<p><strong>创建多个用户账号</strong></p>
<p>如果你是管理员，需要创建大量账号时。不必每次都有<code>useradd</code>命令添加用户。将用户信息存放在指定文件，然后用脚本进行处理就可以了。</p>
<p>用户信息的格式如下：</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">userid,<span class="built_in"> user </span>name</span><br></pre></td></tr></table></figure>
<p>第一个是你为用户选择的id，第二个是用户的全名。这是<code>csv</code>文件格式。</p>
<p>为了能够读取它，我们使用以下命令：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">while IFS=',' read -r userid name</span><br></pre></td></tr></table></figure>
<p><code>read</code>命令会自动获取<code>.csv</code>文本文件的下一行内容，所以不用再写一个循环来处理。当<code>read</code>命令返回<code>FALSE</code>时（也就是读完了），<code>while</code>命令就会退出。</p>
<p>为了把数据从文件导向<code>while</code>命令，只要再<code>while</code>命令尾部加一个重定向符号。</p>
<p>处理过程写成脚本如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> process new user accounts</span></span><br><span class="line"></span><br><span class="line">input="users.csv"</span><br><span class="line">while IFS=',', read -r userid name</span><br><span class="line">do</span><br><span class="line">trueecho "adding $userid"</span><br><span class="line">trueuseradd -c "$name" -m $userid</span><br><span class="line">done &lt; "$input"</span><br></pre></td></tr></table></figure>

      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../categories/Linux杂烩/shell编程/">shell编程</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/bash-shell/">bash shell</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/shell笔记/">shell笔记</a></li></ul>
    </div>

      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
    <article id="post-basic-shell" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="../../2017/08/11/basic-shell/" class="article-date">
      <time datetime="2017-08-10T16:00:00.000Z" itemprop="datePublished">2017-08-11</time>
</a>

 
    <a href="../../2017/08/11/basic-shell/#comments" title="查看评论">
        <i class="fa fa-comments-o" aria-hidden="true"></i>
        <span class="count-comment"></span>
        
        
            <span class="disqus-comment-count" data-disqus-identifier="2017/08/11/basic-shell/"></span>
        
    </a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="../../2017/08/11/basic-shell/">构建基本shell脚本</a>
    </h1>
  

      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <a id="more"></a>
<blockquote>
<p><strong>内容</strong></p>
<ul>
<li>使用多个命令</li>
<li>创建脚本文件</li>
<li>显示消息</li>
<li>使用变量</li>
<li>输入输出重定向</li>
<li>管道</li>
<li>数学运算</li>
<li>退出脚本</li>
</ul>
</blockquote>
<h3 id="使用多个命令"><a href="#使用多个命令" class="headerlink" title="使用多个命令"></a>使用多个命令</h3><p>如果多个命令一起使用，可以放在一行并用分号分隔。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~$ date; who</span><br><span class="line">2017年 07月 26日 星期三 09:53:43 CST</span><br><span class="line">wsx      tty7         2017-07-26 09:48 (:0)</span><br></pre></td></tr></table></figure>
<h3 id="创建脚本文件"><a href="#创建脚本文件" class="headerlink" title="创建脚本文件"></a>创建脚本文件</h3><p>在创建脚本文件时，必须在文件的第一行指定要使用的shell，格式为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br></pre></td></tr></table></figure>
<p>脚本文件的第一行中<code>#</code>后的惊叹号会告诉shell使用哪个shell来运行脚本（如果是其他编码语言脚本，像python，第一行类似）。</p>
<p>其他地方的<code>#</code>用作注释行。</p>
<p>添加名为<code>test1</code>的脚本文件，内容为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"><span class="comment"># This script displays the date and who's logged on</span></span><br><span class="line">date</span><br><span class="line">who</span><br></pre></td></tr></table></figure>
<p>现在运行脚本，结果会是：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx<span class="meta">@wsx</span>-<span class="string">ubuntu:</span>~/script_learn$ test1</span><br><span class="line">未找到 <span class="string">'test1'</span> 命令，您要输入的是否是：</span><br><span class="line"> 命令 <span class="string">'testr'</span> 来自于包 <span class="string">'python3-testrepository'</span> (main)</span><br><span class="line"> 命令 <span class="string">'testr'</span> 来自于包 <span class="string">'python-testrepository'</span> (universe)</span><br><span class="line"> 命令 <span class="string">'test'</span> 来自于包 <span class="string">'coreutils'</span> (main)</span><br><span class="line">test1：未找到命令</span><br></pre></td></tr></table></figure>
<p>我们现在需要做的是让bash shell能够找到我们的脚本文件。shell会通过<code>PATH</code>环境变量来查找命令，我们可以看看：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $PATH</span><br><span class="line">/home/wsx/Anaconda/bin:/home/wsx/Anoconda/ENTER/bin:/usr/lib/jvm/default-java/bin:/home/wsx/bin:/home/wsx/Anaconda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin</span><br></pre></td></tr></table></figure>
<p>很显然，我们的文件没有在这些目录范围内。要让shell找到test1脚本，我们可以采取以下两种做法之一：</p>
<ul>
<li>将shell脚本文件所处的目录添加到<code>PATH</code>环境变量中；</li>
<li>在提示符中用绝对路径或相对路径来引用shell脚本文件。</li>
</ul>
<p>第二种方法比较简单，我们在这里试试：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1</span><br><span class="line">bash: ./test1: 权限不够</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ll test1 # 发现权限不够，查看文件的权限</span><br><span class="line">-rw-rw-r-- 1 wsx wsx 73 7月  26 10:03 test1</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test1 # 修改权限，添加可执行属性</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1 # 成功运行脚本</span><br><span class="line">2017年 07月 26日 星期三 10:09:23 CST</span><br><span class="line">wsx      tty7         2017-07-26 09:48 (:0)</span><br></pre></td></tr></table></figure>
<h3 id="显示消息"><a href="#显示消息" class="headerlink" title="显示消息"></a>显示消息</h3><p>在<code>echo</code>命令后面加上一个字符串，就能显示出这个文本字符串。这种方式可以添加自己的文本消息来告诉脚本用户脚本正在做什么。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo This is a test</span><br><span class="line">This is a test</span><br></pre></td></tr></table></figure>
<p>如果文本本身带有字符串，我们需要<strong>用单引号或双引号来划定文本字符串</strong>。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo "Let's see if this'll work"</span><br><span class="line">Let's see if this'll work</span><br></pre></td></tr></table></figure>
<p>我们修改下之前的test1文件，增加消息显示：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> This script displays the date and who<span class="string">'s logged on</span></span></span><br><span class="line">echo The time and date are:</span><br><span class="line">date</span><br><span class="line">echo "Let's see who's logged into the system"</span><br><span class="line">who</span><br></pre></td></tr></table></figure>
<p>运行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1</span><br><span class="line">The time and date are:</span><br><span class="line">2017年 07月 26日 星期三 10:17:59 CST</span><br><span class="line">Let's see who's logged into the system</span><br><span class="line">wsx      tty7         2017-07-26 09:48 (:0)</span><br></pre></td></tr></table></figure>
<p><strong>如果想把文本字符串和命令输出显示在同一行中</strong>，可以用<code>echo</code>语句的<code>-n</code>参数。需要在字符串的两侧加上引号，并且保证字符串尾部有一个空格（不然字符串和命令输出就粘连到一起了）。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> This script displays the date and who<span class="string">'s logged on</span></span></span><br><span class="line">echo -n "The time and date are: "</span><br><span class="line">date</span><br><span class="line">echo  "Let's see who's logged into the system: "</span><br><span class="line">who</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> 运行结果输出</span></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test1</span><br><span class="line">The time and date are: 2017年 07月 26日 星期三 10:24:04 CST</span><br><span class="line">Let's see who's logged into the system:</span><br><span class="line">wsx      tty7         2017-07-26 09:48 (:0)</span><br></pre></td></tr></table></figure>
<h3 id="使用变量"><a href="#使用变量" class="headerlink" title="使用变量"></a>使用变量</h3><p>变量允许我们临时性地将信息存储在shell脚本中，以便和脚本中的其他命令一起使用。</p>
<p><strong>环境变量</strong></p>
<p>shell维护着一组环境变量，用来记录特定的系统信息。比如系统的名称、登录到系统上的用户名、用户的系统ID(也称为UID)、用户默认主目录以及shell查找程序的搜索路径。</p>
<p>使用<code>set</code>命令显示一份完整的当前环境变量列表。<code>env</code>与<code>printenv</code>命令都可以显示全局变量。（这些命令输出结果比较多，不展示了。之前关于环境变量的笔记有比较详细的描述。）</p>
<p>在环境变量名称之前加上美元符可以使用这些环境变量。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test2</span><br><span class="line"><span class="meta">#</span><span class="bash">! /bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> display user information from the system</span></span><br><span class="line">echo "User info for userid: $USER"</span><br><span class="line">echo UID: $UID</span><br><span class="line">echo HOME: $HOME</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test2</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test2</span><br><span class="line">User info for userid: wsx</span><br><span class="line">UID: 1000</span><br><span class="line">HOME: /home/wsx</span><br></pre></td></tr></table></figure>
<p>可以想象的到，如果我们想要使用实际的美元符而不是引用变量，肯定会出问题。这时候我们需要在美元符前面加上<code>\</code>进行转义，以显示美元符本身。</p>
<p><strong>用户变量</strong></p>
<p>使用等号将值赋给用户变量。<strong>注意，在变量、等号和值之间不能出现空格！</strong>这个是初学者常见的一个问题，本人也非常不太适应这个。因为在其他语言中不区分等号两边的空格，相信接触过其他脚本的朋友们肯定有习惯打空格使代码美观的，这在bash shell中是万万行不通滴。</p>
<p>一个使用的例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test3</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> testing variables</span></span><br><span class="line">days=10</span><br><span class="line">guest="Katie"</span><br><span class="line">echo "$guest checked in $days days ago"</span><br><span class="line">days=5</span><br><span class="line">guest="Jessica"</span><br><span class="line">echo "$guest checked in $days days ago"</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test3</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test3</span><br><span class="line">Katie checked in 10 days ago</span><br><span class="line">Jessica checked in 5 days ago</span><br></pre></td></tr></table></figure>
<p>变量每次被引用时，都会输出当前赋给它的值。重要的是要记住，引用一个变量值时需要使用美元符，而引用变量来对其进行赋值时则不需要使用美元符。</p>
<h3 id="命令替换"><a href="#命令替换" class="headerlink" title="命令替换"></a>命令替换</h3><p>shell脚本最有用的特性之一就是可以从命令输出中提取信息，并将其赋给变量。</p>
<p>有两种方法可以将命令输出赋给变量：</p>
<ul>
<li>反引号字符(`)</li>
<li>$()格式</li>
</ul>
<figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">要么用一对反引号把整个命令行命令围起来：</span><br><span class="line">testing=`date`</span><br><span class="line">要么使用$()格式</span><br><span class="line">testing=<span class="variable">$(date)</span></span><br></pre></td></tr></table></figure>
<p>下面是一个例子，在脚本中通过命令替换获得当前日期并用它来生成唯一文件名：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test4</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> copy the /usr/bin directory listing to a <span class="built_in">log</span> file</span></span><br><span class="line">today=$(date +%y%m%d)</span><br><span class="line">ls /usr/bin -al &gt; log.$today</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test4</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test4</span><br></pre></td></tr></table></figure>
<h3 id="重定向输入和输出"><a href="#重定向输入和输出" class="headerlink" title="重定向输入和输出"></a>重定向输入和输出</h3><p>通过几个操作符进行重定向，我们可以将命令的结果输出到另外的位置（文件）。当然，重定向可以用于输入。</p>
<p><strong>输出重定向</strong></p>
<p>最基本的操作符是<code>&gt;</code>。比如我们想要输出命令结果到一个指定文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ date &gt; test6</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ls -l test6</span><br><span class="line">-rw-rw-r-- 1 wsx wsx 43 7月  26 16:42 test6</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test6</span><br><span class="line">2017年 07月 26日 星期三 16:42:34 CST</span><br></pre></td></tr></table></figure>
<p>如果想要将命令的输出追加到已有文件中，需要用双大于号（&gt;&gt;）来追加数据。</p>
<p><strong>输入重定向</strong></p>
<p>输入重定向和输出重定向正好相反。输入重定向将文件的内容重定向到命令，而非将命令的输出重定向到文件。</p>
<p>使用的符号是小于号（&lt;）。</p>
<blockquote>
<p>一种简单的记忆方法是：在命令行上，命令总是在左侧，而重定向符号“指向”数据流动的方向。小于号说明数据正在从输入文件流向命令。</p>
</blockquote>
<p>比如用wc命令检查文本的行数、词数和字节数。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ wc &lt; test6</span><br><span class="line"> 1  6 43</span><br></pre></td></tr></table></figure>
<p>另一种输入重定向的方法是<strong>内联输入重定向</strong>。它无需使用文件进行重定向，只需要在命令行中指定用于输入重定向的数据即可。它使用的符号是远小于号（&lt;&lt;），除了这个符号，我们还需要指定一个文本标记用来划分输入数据的开始和结尾。任何字符串都可以作为文本标记，但在数据的开始和结尾文本标记必须一致。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ wc &lt;&lt; EOF</span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> <span class="built_in">test</span> string1</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> <span class="built_in">test</span> string2</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> <span class="built_in">test</span> string3</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash"> EOF</span></span><br><span class="line"> 3  6 39</span><br></pre></td></tr></table></figure>
<p>它的形式为：</p>
<figure class="highlight haskell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="title">command</span> &lt;&lt; marker</span><br><span class="line"><span class="class"><span class="keyword">data</span></span></span><br><span class="line"><span class="title">marker</span></span><br></pre></td></tr></table></figure>
<h3 id="管道"><a href="#管道" class="headerlink" title="管道"></a>管道</h3><p>有时候需要将一个命令的输出作为另一个命令的输入。通过<code>|</code>符号分隔命令即可实现管道。</p>
<p>比如我想查看某个文件（test1）的前两行并进行排序，操作如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test1</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> This script displays the date and who<span class="string">'s logged on</span></span></span><br><span class="line">echo -n "The time and date are: "</span><br><span class="line">date</span><br><span class="line">echo  "Let's see who's logged into the system: "</span><br><span class="line">who</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test1 | head -2 | sort</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> This script displays the date and who<span class="string">'s logged on</span></span></span><br></pre></td></tr></table></figure>
<p>管道的强大之处在于可以根据自己的需求灵活地组合和使用各种linux命令工具。这里只是一个简单的例子，要熟练掌握少不了平时多多研究和练习。</p>
<h3 id="执行数学运算"><a href="#执行数学运算" class="headerlink" title="执行数学运算"></a>执行数学运算</h3><p>对shell脚本来说，执行数学运算非常麻烦。有两种实现方式。</p>
<p><strong>expr</strong>命令</p>
<p><code>expr</code>命令允许在命令行上处理数学表达式，但是特别笨拙。（Bourne shell中）</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ exrpr 1 + 5</span><br><span class="line">未找到 'exrpr' 命令，您要输入的是否是：</span><br><span class="line"> 命令 'expr' 来自于包 'coreutils' (main)</span><br><span class="line">exrpr：未找到命令</span><br></pre></td></tr></table></figure>
<p>看到没有，那算了。它基本涉及的操作跟我们使用的其他语言是一致的。但是有些问题需要处理，像<code>*</code>是通配符，在运算是是做乘号处理的，需要进行转义。</p>
<p><strong>使用方括号</strong></p>
<p>bash shell提供了一种更简单的方法来执行数学表达式。在bash中，在将一个数学运算结果赋给某个变量时，可以用美元符和方括号（$[operator]）将数学表达式围起来。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ var1=$[1+5]</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $var1</span><br><span class="line">6</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ var2=$[$var1+2]</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $var2</span><br><span class="line">8</span><br></pre></td></tr></table></figure>
<p>这种方式不仅方便，而且因为在方括号内，不会让shell误解乘号或其他符号。</p>
<p>但bash shell计算有一个主要限制：<strong>它只支持整数运算！</strong></p>
<p><strong>浮点解决方案</strong></p>
<p>最常见的方案是用内建的bash计算器。它实际上是一门编程语言，它允许在命令行中输入浮点表达式，然后解释并计算该表达式，最后返回结果。bash计算器能够识别：</p>
<ul>
<li>数字（整数和浮点数）</li>
<li>变量（简单变量和数组）</li>
<li>注释（/<em> </em>/开始的行）</li>
<li>表达式</li>
<li>编程语句</li>
<li>函数</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ bc</span><br><span class="line">bc 1.06.95</span><br><span class="line">Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.</span><br><span class="line">This is free software with ABSOLUTELY NO WARRANTY.</span><br><span class="line">For details type `warranty'.</span><br><span class="line">12 * 5.4</span><br><span class="line">64.8</span><br><span class="line">3.156 * (3 + 5)</span><br><span class="line">25.248</span><br><span class="line">quit</span><br></pre></td></tr></table></figure>
<p>在脚本中使用bc</p>
<p>可以用命令替换运行bc命令，并将输出赋给一个变量。基本格式如下：</p>
<figure class="highlight gams"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">variable</span>=$(echo <span class="comment">"options; expression"</span> |<span class="comment"> bc)</span></span><br></pre></td></tr></table></figure>
<p>options设置变量，expression参数定义了通过bc执行的数学表达式。</p>
<p>看一个简单实例：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test9</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line">var1=$(echo "scale=4; 3.44/5" | bc)</span><br><span class="line">echo The answer is $var1</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test9</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test9</span><br><span class="line">The answer is .6880</span><br></pre></td></tr></table></figure>
<p>这个例子将<code>scale</code>变量设置为四位小数，并在<code>expression</code>部分指定了特定的运算。</p>
<p>这个方法适用于较短的运算，但有时我们会涉及更多的数字。如果需要进行大量运算，在一个命令行中列出多个表达式就会有点麻烦。</p>
<p>这里有一个解决方法：使用内联输入重定向，将一个文件重定向到bc命令来处理。格式为：</p>
<figure class="highlight gauss"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">variable=$(bc &lt;&lt; <span class="built_in">EOF</span></span><br><span class="line">options</span><br><span class="line"><span class="built_in">statements</span></span><br><span class="line">expressions</span><br><span class="line"><span class="built_in">EOF</span>)</span><br></pre></td></tr></table></figure>
<p><code>EOF</code>文本字符串标识了内联重定向数据的起始。注意，仍然需要命令替换符号将bc命令的输出赋给变量。</p>
<p>下面是一个例子：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test10</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"></span><br><span class="line">var1=10.46</span><br><span class="line">var2=43.67</span><br><span class="line">var3=33.2</span><br><span class="line">var4=71</span><br><span class="line"></span><br><span class="line">var5=$(bc &lt;&lt;EOF</span><br><span class="line">scale=4</span><br><span class="line">a1 = ( $var1 * $var2)</span><br><span class="line">b1 = ( $var3 * $var4)</span><br><span class="line">a1 + b1</span><br><span class="line">EOF</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">echo The final answer for this mess is $var5</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test10</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test10</span><br><span class="line">The final answer for this mess is 2813.9882</span><br></pre></td></tr></table></figure>
<p>在普通的shell脚本中，数字默认当做字符串处理。这也是为什么我们脚本处理计算麻烦和我们需要特定的工具和方法来进行处理。一定要注意区分。</p>
<h3 id="退出脚本"><a href="#退出脚本" class="headerlink" title="退出脚本"></a>退出脚本</h3><p>前面运行的脚本都是命令执行完成，脚本自动结束。其实我们可以用更为优雅的方式告诉shell命令运行完成，因为每个命令都使用<strong>退出状态码（exit status）</strong>，它是一个0-255的整数值，我们可以捕获这个值并在脚本中使用。</p>
<p>Linux提供了一个专门的变量<code>$?</code>来保存上个已执行命令的退出状态码。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ date</span><br><span class="line">2017年 07月 27日 星期四 10:44:18 CST</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $?</span><br><span class="line">0</span><br></pre></td></tr></table></figure>
<p>按照惯例，一个成功结束的命令的退出状态码是0。如果有错误，则显示一个正数值。</p>
<p>Linux错误退出状态码没有什么标准，但有一些参考：</p>
<table>
<thead>
<tr>
<th>状态码</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>命令成功结束</td>
</tr>
<tr>
<td>1</td>
<td>一般性未知错误</td>
</tr>
<tr>
<td>2</td>
<td>不适合的shell命令</td>
</tr>
<tr>
<td>126</td>
<td>命令不可执行</td>
</tr>
<tr>
<td>127</td>
<td>没找到命令</td>
</tr>
<tr>
<td>128</td>
<td>无效的退出参数</td>
</tr>
<tr>
<td>128+x</td>
<td>与Linux信号x相关的严重错误</td>
</tr>
<tr>
<td>130</td>
<td>通过Ctrl+C终止的命令</td>
</tr>
<tr>
<td>255</td>
<td>正常范围之外的退出状态码</td>
</tr>
</tbody>
</table>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ asfg</span><br><span class="line">未找到 'asfg' 命令，您要输入的是否是：</span><br><span class="line"> 命令 'asdfg' 来自于包 'aoeui' (universe)</span><br><span class="line">asfg：未找到命令</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $?</span><br><span class="line">127</span><br></pre></td></tr></table></figure>
<p><strong>exit命令</strong></p>
<p>默认，shell脚本会以脚本最后的一个命令的退出状态码退出。</p>
<p>但是我们可以改变这种默认行为，返回自己的退出状态码。exit命令允许在脚本结束时指定一个状态退出码。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">wsx@wsx-ubuntu:~/script_learn$ cat test13</span><br><span class="line"><span class="meta">#</span><span class="bash">!/bin/bash</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> testing the <span class="built_in">exit</span> status</span></span><br><span class="line">var1=10</span><br><span class="line">var2=30</span><br><span class="line">var3=$[$var1 + $var2]</span><br><span class="line">echo The answer is $var3</span><br><span class="line">exit 5</span><br><span class="line"></span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ chmod u+x test13</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ ./test13</span><br><span class="line">The answer is 40</span><br><span class="line">wsx@wsx-ubuntu:~/script_learn$ echo $?</span><br><span class="line">5</span><br></pre></td></tr></table></figure>
<p>注意最大255，如果大于它，得到的是求模的结果（余数）。</p>

      
    </div>
    
    <div class="article-info article-info-index">
      
      
    <div class="article-category tagcloud">
    <a class="article-category-link" href="../../categories/Linux杂烩/">Linux杂烩</a><a class="article-category-link" href="../../categories/Linux杂烩/shell编程/">shell编程</a>
    </div>


      
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/bash-shell/">bash shell</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="../../tags/shell笔记/">shell笔记</a></li></ul>
    </div>

      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>









  
  
    <nav id="page-nav">
      <a class="extend prev" rel="prev" href="../../index.html">&laquo; Prev</a><a class="page-number" href="../../index.html">1</a><span class="page-number current">2</span>
    </nav>
  
</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                <i class="fa fa-copyright"></i> 
                2017-2018 王诗翔
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a>  Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题  v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i>
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>| </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit"  title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>
    </div>
    
    <script src="../../js/GithubRepoWidget.js"></script>

<script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script>

    <script>
        $(document).ready(function() {
            var iPad = window.navigator.userAgent.indexOf('iPad');
            if (iPad > -1 || $(".left-col").css("display") === "none") {
                var bgColorList = ["#9db3f4", "#414141", "#e5a859", "#f5dfc6", "#c084a0", "#847e72", "#cd8390", "#996731"];
                var bgColor = Math.ceil(Math.random() * (bgColorList.length - 1));
                $("body").css({"background-color": bgColorList[bgColor], "background-size": "cover"});
            }
            else {
                var backgroundnum = 2;
                var backgroundimg = "url(/background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum));
                $("body").css({"background": backgroundimg, "background-attachment": "fixed", "background-size": "cover"});
            }
        })
    </script>


    

    
        <script id="dsq-count-scr" src="//Cloudberry.disqus.com/count.js" async></script>
        <script>
            if ($(".left-col").is(":visible")) {
                var $disqusCount = $(".disqus-comment-count");
                $disqusCount.bind("DOMNodeInserted", function(e) {
                    var num = $(this).text().replace(/[^0-9]/ig,"");
                    if (num > 0) {
                        $(this).siblings(".count-comment").text(num);
                    }
                    $(this).remove();
                })
            } else {
                $(".disqus-comment-count").remove();
            }
        </script>
     




    <script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


<div class="scroll" id="scroll">
    <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a>
    <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    // Open in New Window
    
        var oOpenInNew = {
             github: ".github-widget a", 
            
             post: ".article-entry a[href], .copyright a[href]", 
            
            
            
             archives: ".archive-article-title", 
             miniArchives: "a.post-list-link", 
            
             friends: "#js-friends a", 
             socail: ".social a" 
        }
        for (var x in oOpenInNew) {
            $(oOpenInNew[x]).attr("target", "_blank");
        }
    
</script>

    <script>
        var originTitle = document.title;
        var titleTime;
        document.addEventListener("visibilitychange", function() {
            if (document.hidden) {
                document.title = "(つェ⊂) 我藏好了哦~ " + originTitle;
                clearTimeout(titleTime);
            }
            else {
                document.title = "(*´∇｀*) 被你发现啦~ " + originTitle;
                titleTime = setTimeout(function() {
                    document.title = originTitle;
                }, 2000);
            }
        })
    </script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  </div>
</body>
</html>